﻿using B.S.BasicData.Domain.Entity;
using B.S.BasicData.Infastructure.Interface;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B.S.BasicData.Infastructure.Implement
{
    public class BaseRepository<T>:IBaseRepository<T> where T : BaseEntity
    {
        MyDbContext _db;

        public BaseRepository(MyDbContext db)
        {
            _db = db;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public int Add(T entity)
        {
            _db.Set<T>().Add(entity);
            return _db.SaveChanges();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Delete(T entity)
        {
            _db.Set<T>().Remove(entity);
            return _db.SaveChanges();
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public int DeleteRange(IEnumerable<T> entities)
        {
            _db.Set<T>().RemoveRange(entities);
            return _db.SaveChanges();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetAll()
        {
            return _db.Set<T>().AsQueryable();
        }

        /// <summary>
        /// 条件表达试查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetValue(long id)
        {
            return _db.Set<T>().Find(id);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Update(T entity)
        {
            _db.Set<T>().Update(entity);
            return _db.SaveChanges();
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public int UpdateRange(IEnumerable<T> entities)
        {
            _db.Set<T>().UpdateRange(entities);
            return _db.SaveChanges();
        }
    }
}
